package com.dbapp.garden.controller.teaching;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.controller.student.StudentInfoController;
import com.dbapp.garden.entity.GardenCareStudentSignIn;
import com.dbapp.garden.entity.GardenStudentInfo;
import com.dbapp.garden.service.GardenCareStudentSignInService;
import com.dbapp.garden.service.GardenStudentInfoService;
import com.dbapp.garden.service.GardenStudentStateService;
import com.dbapp.garden.vm.StudentSignInVm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * @author by gangzi on 2017/11/14.
 */
@Controller
public class GardenCareStudentController {

    private static final Logger log = LoggerFactory.getLogger(StudentInfoController.class);

    private static final String COMMA=",";

    @Autowired
    private GardenStudentInfoService stuService;

    @Autowired
    private GardenStudentStateService stuStateService;

    @Autowired
    private GardenCareStudentSignInService signInService;

    @GetMapping("/care")
    public String toCareStudent(HttpServletRequest request) {
        return "teaching/carestudent";
    }

    @PostMapping("/signinstudentlist")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO')")
    public Map<String, ?> careStudentList(HttpServletRequest request, Integer signType, String param) {

        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");

        paramMap.clear();
        paramMap.put("search", sSearch);
        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength);
        paramMap.put("signType", signType);

        List<GardenStudentInfo> studentList = stuService.getSignInStudentList(paramMap);
        Integer count = stuService.getSignInStudentCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, studentList, "");
    }

    @PostMapping("/signinrecordlist")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO')")
    public Map<String, ?> signInRecordList(HttpServletRequest request, Integer signType, String param) {

        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");

        paramMap.clear();
        paramMap.put("search", sSearch);
        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength);
        paramMap.put("signType", signType);

        List<GardenCareStudentSignIn> studentList = signInService.getSignInRecordList(paramMap);
        Integer count = signInService.getSignInRecordCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, studentList, "");
    }


    @PostMapping("/carestudentsign")
    @ResponseBody
    public Map<String, ?> careStudentSignIn(HttpServletRequest request,@RequestBody @Valid StudentSignInVm signInVm ) {

        String stuId=signInVm.getStudentId();
        //批量签到
        if (stuId.contains(COMMA)) {
            List<GardenCareStudentSignIn> signInList = new ArrayList<>();
            String[] stuIds=stuId.split(",");
            Arrays.stream(stuIds).filter(s -> StringUtils.isNotEmpty(s)).forEach(s -> {
                Integer id = Integer.parseInt(s);
                GardenCareStudentSignIn signIn = new GardenCareStudentSignIn();
                signIn.setStudentId(id);
                signIn.setSignInTime(new Date());
                signIn.setSignInType(signInVm.getSignInType());

                signIn.setGardenId(0);

                signInList.add(signIn);
            });

            Integer result = signInService.batchInsert(signInList);
            if (result != null && result > 0) {
                return RenderJSON.makeStandMap(1, "恭喜您，成功签到" + result + "个学员", "ok");
            } else {
                return RenderJSON.makeStandMap(1, "对不起，批量签到失败", "error");
            }

        } else {
            //单个签到
            Integer id = Integer.parseInt(stuId);
            GardenCareStudentSignIn signIn = new GardenCareStudentSignIn();
            signIn.setStudentId(id);
            signIn.setSignInTime(new Date());
            signIn.setSignInType(signInVm.getSignInType());

            Integer result = signInService.save(signIn);
            if (result != null && result > 0) {
                return RenderJSON.makeStandMap(1, "恭喜您，签到成功", "ok");
            } else {
                return RenderJSON.makeStandMap(1, "对不起，签到失败", "error");
            }
        }


    }

    @DeleteMapping("/carestudentsign/{id}")
    @ResponseBody
    public Map<String, ?> deleteStudentSignIn(HttpServletRequest request,@PathVariable("id") Integer id) {
        GardenCareStudentSignIn signIn=signInService.findById(id);
        if (signIn==null){
            return RenderJSON.makeStandMap(1, "对不起，签到记录不存在，删除失败", "error");
        }
        Integer result = signInService.delete(id);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，撤销成功", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，撤销失败", "error");
        }
    }
}
